<template>
    <div class="personalData">
        <div class="group">
            <div class="head">基础信息</div>
            <van-cell-group>
                <van-cell title="头像" is-link class="van-cell-avatar" @click="showAvatarActionSheet = true">
                    <div class="avatar"><img :src="userAvatar" alt=""></div>
                </van-cell>
                <van-cell title="账号" :value="username"></van-cell>
                <van-cell title="昵称" :value="nickname" is-link @click="$router.push('/modifyNickname')"></van-cell>
                <van-cell title="简介" :value="profile" is-link @click="$router.push('/modifyProfile')"></van-cell>
                <van-cell title="收货地址" is-link></van-cell>
            </van-cell-group>
        </div>
        <div class="group">
            <div class="head">{{accountBind.name}}</div>
            <van-cell-group>
                <van-cell :title="item.title" @click="bindFor(item)" is-link v-for="(item,index) in accountBind.value" :key="index">
                    <template #icon>
                        <div class="img"><img :src="item.img" alt=""></div>
                    </template>
                    <div class="bindInfo" v-if="item.title=='手机'">
                        <span class="bind">{{phone.slice(0,3)+'****'+phone.slice(7,11)}}</span>
                    </div>
                    <div class="bindInfo" v-else>
                        <span class="bind" v-if="item.value">已绑定</span>
                        <span v-else>未绑定</span>
                    </div>
                </van-cell>
            </van-cell-group>
        </div>
        <van-action-sheet
            v-model:show="showAvatarActionSheet"
            cancel-text="取消"
            close-on-click-action
        >
            <div class="actionItem">拍一张</div>
            <div class="actionItem">
                <van-uploader name="avatar" :max-count="1" :before-read="beforeReadAvatar" :after-read="afterReadAvatar" >从手机相册选择</van-uploader>
            </div>
        </van-action-sheet>
    </div>
</template>

<script>
import { ref, reactive, toRefs, watch, inject } from 'vue';

import { useStore } from 'vuex';
import { useRouter } from 'vue-router';
import { modifyAvatar, modifyBindTaoBao, modifyBindAliPay, modifyBindWeChat } from '@/api/user';
import { showLoadingToast, closeToast, showConfirmDialog, showToast } from 'vant';
export default {
    name:'PersonalData',
    setup(){
        const store = useStore();
        const router = useRouter();
        
        const reload = inject('reload');
        
        const token = reactive(JSON.parse(store.state.token));
        console.log('token',token)
        const { username, password, nickname, profile, phone, email, bindTaoBao, bindAliPay, bindWeChat, avatar, register_time } = toRefs(token);
        const userAvatar = ref('http://127.0.0.1:3000/images/user/userAvatar/'+avatar.value);
        watch(userAvatar,(newVal,oldVal)=>{
            console.log('userAvatar',newVal);
        })

        const accountBind = reactive({
            name:'账号绑定',
            value:[
                {
                    title:'手机',
                    img:require('@/assets/img/icon/phone.png'),
                    value:phone.value.slice(0,3)+'****'+phone.value.slice(7,11)
                },
                {
                    title:'淘宝',
                    img:require('@/assets/img/icon/taobao.png'),
                    value:bindTaoBao.value
                },
                {
                    title:'支付宝',
                    img:require('@/assets/img/icon/alipay.png'),
                    value:bindAliPay.value
                },
                {
                    title:'微信',
                    img:require('@/assets/img/icon/wechat.png'),
                    value:bindWeChat.value
                },
            ]
        })
        
        const showAvatarActionSheet = ref(false);  // 显示动态面板
        const beforeReadAvatar = (file) => {
            if (file.type !== 'image/jpeg' && file.type !== 'image/jpg' && file.type !== 'image/webp' && file.type !== 'image/png') {
                showToast('请上传 jpg/jpeg/png/webp 格式图片');
                return false;
            }
            return true;
        }
        const afterReadAvatar = (e) => {
            // 此时可以自行将文件上传至服务器
            console.log(e.file);
            let data = new FormData();
            data.append('id',localStorage.getItem('userId'))
            data.append('avatar',e.file);

            modifyAvatar(data).then(res=>{
                console.log(res);
                showAvatarActionSheet.value = false;

                showLoadingToast({ forbidClick: true });
                setTimeout(() => {
                    closeToast();
                    if(res.code == '1500'){
                        userAvatar.value = 'http://127.0.0.1:3000/images/user/userAvatar/'+res.data;
                        token.avatar = res.data
                        store.commit('SET_TOKEN',JSON.stringify(token));
                    }
                }, 500);
            }).catch(error=>{
                console.log(error)
            })
        };
        const bindFor = (item) => {
            let value = item.value;
            console.log(value)
            if(value){
                showConfirmDialog({
                    title: '解除绑定',
                    message: `确定要解除账号与${item.title}的关联吗？解除后将无法使用淘宝登录此账号`,
                })
                .then(() => {
                    // on confirm
                    if(item.title == '淘宝'){
                        modifyBindTaoBao({
                            id:localStorage.getItem('userId'),
                            bindTaoBao:!value
                        }).then(res=>{
                            console.log(res)
                            if(res.code == '1800') {
                                token.bindTaoBao = !bindTaoBao.value;
                                store.commit('SET_TOKEN',JSON.stringify(token));
                                console.log(JSON.parse(store.state.token))
                                showToast('设置成功',{duration:1500});
                                reload();
                            }
                        }).catch(error=>{
                            console.log(error)
                        })
                    }
                    if(item.title == '支付宝'){
                        modifyBindAliPay({
                            id:localStorage.getItem('userId'),
                            bindAliPay:!value
                        }).then(res=>{
                            console.log(res)
                            if(res.code == '1800') {
                                token.bindAliPay = !bindAliPay.value;
                                store.commit('SET_TOKEN',JSON.stringify(token));
                                console.log(JSON.parse(store.state.token))
                                showToast('设置成功',{duration:1500});
                                reload();
                            }
                        }).catch(error=>{
                            console.log(error)
                        })
                    }
                    if(item.title == '微信'){
                        modifyBindWeChat({
                            id:localStorage.getItem('userId'),
                            bindWeChat:!value
                        }).then(res=>{
                            console.log(res)
                            if(res.code == '1800') {
                                token.bindWeChat = !bindWeChat.value;
                                store.commit('SET_TOKEN',JSON.stringify(token));
                                console.log(JSON.parse(store.state.token))
                                showToast('设置成功',{duration:1500});
                                reload();
                            }
                        }).catch(error=>{
                            console.log(error)
                        })
                    }
                })
                .catch(() => {
                    // on cancel
                });
            }
        }
        return {
            username,
            password,
            nickname,
            profile,
            phone,
            email,
            bindTaoBao,
            bindAliPay,
            bindWeChat,
            avatar,
            register_time,
            userAvatar,
            accountBind,
            showAvatarActionSheet,
            beforeReadAvatar,
            afterReadAvatar,
            bindFor,
        }
    }
}
</script>

<style>
.personalData{
    width: 100%;
    height: 100vh;
    box-sizing: border-box;
    padding-top: 40px;
    display: flex;
    flex-direction: column;
}
.personalData .group{margin-top: 15px;}
.personalData .group:last-child{flex-grow: 1;}
.personalData .group .van-cell-avatar .van-cell__value{display: flex;justify-content: flex-end;}
.personalData .group .van-cell-avatar .van-cell__value .avatar{
    height: 48px;
    width: 48px;
    border-radius: 50%;
    overflow: hidden;
}
.personalData .group .van-cell-avatar .van-cell__value img{width: 100%;height: 100%;}
.personalData .group .head{padding: 15px;color: #666;}
.personalData .van-cell__title{font-size: 16px;}
.personalData .group:first-child .van-cell__title{margin-right: 10px;}
.personalData .group:last-child .van-cell__title{margin-left: 10px;}
.personalData .van-cell__right-icon{margin-left: 10px;}
.personalData .van-cell .img{width: 32px;height: 32px;position: relative;}
.personalData .van-cell:nth-child(2) .img img{
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%,-50%);
    width: 36px;
    height: 36px;
    object-fit: cover;
    object-position: center;
}
.personalData .bindInfo .bind{color: #02b6fd;}
.personalData .bindInfo span{color: #333;}
.personalData .van-action-sheet .actionItem{
    padding: 15px;
    width: 100%;
    box-sizing: border-box;
    text-align: center;
}
</style>